// const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
// const CompressionWebpackPlugin = require('compression-webpack-plugin')
// const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i
// const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
const resolve = dir => require('path').join(__dirname, dir)
// const webpack = require('webpack')
// const path = require('path')
const os = require('os')

// 增加环境变量
// process.env.VUE_APP_VERSION = require('./package.json').version
// process.env.VUE_APP_BUILD_TIME = require('dayjs')().format('YYYY-M-D HH:mm:ss')

// 基础路径 注意发布之前要先修改这里
const publicPath = process.env.VUE_APP_PUBLIC_PATH || '/'

// 获取本机IP
function needHost() {
  let needHost = ''
  try {
    const network = os.networkInterfaces()
    for (const dev in network) {
      network[dev].forEach(alias => {
        if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
          needHost = alias.address
        }
      })
    }
  } catch (e) {
    needHost = 'localhost'
  }
  return needHost
}

module.exports = {
  publicPath, // 根据你的实际情况更改这里
  lintOnSave: undefined,
    // 百度地图配置20180518
 /* externals: {
    "BMap": "BMap"
  }, */
  devServer: {
    publicPath,
    disableHostCheck: true,
    host: needHost(),
    port: 8001,
    proxy: {
      // ---------- 新的代理设置 ----------

      // 可视化API
      viewApi: {
        target: 'http://192.168.20.171:6700',
        ws: true,
        changeOrigin: true,
        pathRewrite: {
          '^/api/viewApi': '/'
        }
      },

      // 登录授权API
      oauthApi: {
        target: 'http://192.168.20.135:5000',
        ws: true,
        changeOrigin: false,
        pathRewrite: {
          '^/api/oauthApi': '/'
        }
      }
    }
    // proxy: 'http://127.0.0.1:9999',
    // proxy: 'http://172.28.228.77:9999',
    //  publicPath: baseUrl // 和 baseUrl 保持一致
  },
  css: {
    loaderOptions: {
      // 设置 scss 公用变量文件
      sass: {
        data: `@import '~@/assets/style/public.scss';`
      }
    }
  },
  transpileDependencies: ['vue-socket.io'],
  configureWebpack: config => {
    // const plugins = []
    // plugins.push(
    //   new CompressionWebpackPlugin({
    //     filename: '[path].gz[query]',
    //     algorithm: 'gzip',
    //     test: productionGzipExtensions,
    //     threshold: 0,
    //     minRatio: 0.8
    //   })
    // )
    // plugins.push(
    //   new webpack.DllReferencePlugin({
    //     context: process.cwd(),
    //     manifest: require(path.join(
    //       process.cwd(),
    //       './public/vendor/vendor-manifest.json'
    //     ))
    //   })
    // )
    // plugins.push(
    //   new AddAssetHtmlPlugin({
    //     // dll文件位置
    //     filepath: path.resolve(__dirname, './public/vendor/*.js'),
    //     // dll 引用路径
    //     publicPath: './vendor',
    //     // dll最终输出的目录
    //     outputPath: './vendor'
    //   })
    // )

    // config.plugins = [...config.plugins, ...plugins]
    config.externals = {
      'AMap': 'AMap', // 高德地图配置
      'AMapUI': 'AMapUI'
    }
  },
  // webpack 设置
  // 默认设置: https://github.com/vuejs/vue-cli/tree/dev/packages/%40vue/cli-service/lib/config/base.js
  chainWebpack: config => {
    // config.plugin('webpack-bundle-analyzer').use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
    /**
     * 删除懒加载模块的 prefetch preload，降低带宽压力
     * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#prefetch
     * https://cli.vuejs.org/zh/guide/html-and-static-assets.html#preload
     * 而且预渲染时生成的 prefetch 标签是 modern 版本的，低版本浏览器是不需要的
     */
    config.plugins.delete('prefetch').delete('preload')
    // 解决 cli3 热更新失效 https://github.com/vuejs/vue-cli/issues/1559
    config.resolve.symlinks(true)
    config
    // 开发环境
      .when(
        process.env.NODE_ENV === 'development',
        // sourcemap不包含列信息cheap-source-map
        config => config.devtool('cheap-source-map')
      )
    config.optimization.splitChunks({
      cacheGroups: {
        vendor: {
          chunks: 'all',
          test: /[\\/](node_modules)[\\/]/,
          name: 'vendor',
          minChunks: 1,
          maxInitialRequests: 5,
          minSize: 0,
          priority: 100
        },
        common: {
          chunks: 'all',
          test: /[\\/]src[\\/]js[\\/]/,
          name: 'common',
          minChunks: 2,
          maxInitialRequests: 5,
          minSize: 0,
          priority: 60
        },
        styles: {
          name: 'styles',
          test: /\.(sa|sc|c)ss$/,
          chunks: 'all',
          enforce: true
        },
        runtimeChunk: {
          name: 'manifest'
        }
      }
    })
    // config.optimization.minimizer([
    //   new UglifyJsPlugin({
    //     uglifyOptions: {
    //       sourceMap: false,
    //       parallel: true,
    //       cache: true,
    //       // 移除 console
    //       // 其它优化选项 https://segmentfault.com/a/1190000010874406
    //       compress: {
    //         warnings: false,
    //         drop_console: true,
    //         drop_debugger: true,
    //         pure_funcs: ['console.log']
    //       }
    //     }
    //   })
    // ])
    // js
    config.module
      .rule('js')
      .test(/\.js$/)
      .use('thread-loader')
      .loader('thread-loader')
      .options({
        options: {
          // 产生的 worker 的数量，默认是 cpu 的核心数
          workers: os.cpus().length,
          // 一个 worker 进程中并行执行工作的数量
          // 默认为 20
          workerParallelJobs: 100,
          // 额外的 node.js 参数
          workerNodeArgs: ['--max-old-space-size', '1024'],
          // 闲置时定时删除 worker 进程
          // 默认为 500ms
          // 可以设置为无穷大， 这样在监视模式(--watch)下可以保持 worker 持续存在
          poolTimeout: 2000
        }
      })
      .end()
    // markdown
    // config.module
    //   .rule('md')
    //   .test(/\.md$/)
    //   .use('text-loader')
    //   .loader('text-loader')
    //   .end()
    // i18n
    // config.module
    //   .rule('i18n')
    //   .resourceQuery(/blockType=i18n/)
    //   .use('i18n')
    //   .loader('@kazupon/vue-i18n-loader')
    //   .end()
    // svg
    // const svgRule = config.module.rule('svg')
    // svgRule.uses.clear()
    // svgRule.include
    //   .add(resolve('src/assets/svg-icons/icons'))
    //   .end()
    //   .use('svg-sprite-loader')
    //   .loader('svg-sprite-loader')
    //   .options({
    //     symbolId: 'd2-[name]'
    //   })
    //   .end()
    // image exclude
    // const imagesRule = config.module.rule('images')
    // imagesRule
    //   .test(/\.(png|jpe?g|gif|webp|svg)(\?.*)?$/)
    //   .exclude.add(resolve('src/assets/svg-icons/icons'))
    //   .end()
    // 重新设置 alias
    config.resolve.alias
      .set('@', resolve('src'))
      .set('@enums', resolve('src/enums'))
      .set('@assets', resolve('src/assets'))
      .set('@components', resolve('src/views/components'))
      .set('@api', resolve('src/api'))
      .set('@const', resolve('src/const'))
      .set('@supportConst', resolve('src/const/support'))
      .set('@questionConst', resolve('src/const/question'))
      .set('@pagesConst', resolve('src/const/pages'))
      .set('@supportApi', resolve('src/api/support'))
      .set('@questionApi', resolve('src/api/question'))
      .set('@gridApi', resolve('src/api/grid'))
      .set('@messageApi', resolve('src/api/message'))
      .set('@flowApi', resolve('src/api/flow'))
      .set('@smsApi', resolve('src/api/sms'))
      .set('@videoApi', resolve('src/api/video'))
      .set('@carApi', resolve('src/api/car'))
      .set('@project', resolve('src/project'))
    // node
    // config.node.set('__dirname', true).set('__filename', true)
    // babel-polyfill 加入 entry
    // const entry = config.entry('app')
    // entry.add('babel-polyfill').end()
    // 判断环境加入模拟数据
    // if (process.env.VUE_APP_BUILD_MODE !== 'nomock') {
    //   entry.add('@/mock').end()
    // }
  }
}
